package com.dream.netty.nettyclientweb.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author song_
 *
 * */
@Component
public class NettyClient implements SmartLifecycle {

    private static EventLoopGroup group = null ;

    private static Channel channel = null ;

    @Override
    public void start() {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyClientHandler());
                    }
                });
        channel = bootstrap.connect("127.0.0.1",8080).channel();
    }

    @Override
    public void stop() {
        if (channel != null){
            channel.close();
        }
        if (group != null){
            group.shutdownGracefully();
        }
    }

    @Override
    public boolean isRunning() {
        return false;
    }

    public void sendMessage(String message){
        if (StringUtils.isEmpty(message)){
            message = "default message";
        }
        channel.writeAndFlush(Unpooled.copiedBuffer(message.getBytes()));
    }
}
